<template lang="html">
  <Layout style="margin: -10px -20px -20px;">
    <Sider :style="{backgroundColor: '#fff'}">
      <Menu theme="light" width="auto" active-name="">
        <div>
            <div class="ml-col-group-list">
              创建的歌单 <a class="ml-col-add" @click="toggleIpt"><Icon type="plus"></Icon></a>
            </div>
            <div class="ml-col-addText" ref="ipt" :style="{display: 'none'}">
                <Input placeholder="输入歌单名" @on-blur="handleAddText"></Input>
            </div>
            <MenuItem class="ml-menu" :name="ml.name" @click.native="openMusicListInfo(ml)" v-for="ml in musicListsByMyself">
                <Icon type="document-text"></Icon>
                {{ ml.name }}
                <a class="ml-col-rm" @click.stop="removeMusicList(ml.id)"><Icon type="minus"></Icon></a>
            </MenuItem>
            <div v-show="musicListsByMyself.length === 0" class="ml-no-data">
              <Icon type="ios-information"></Icon>暂无歌单！
            </div>
        </div>
      </Menu>
    </Sider>
    <Layout :style="{padding: '10px 20px 0'}">
      <h2 class="ml-col-title">推荐歌单
        <span :style="{float: 'right'}" v-show="mlRecommands.totalPages">
          <Button :disabled="mlRecommands.page === 0" shape="circle" size="small" type="text" @click="mlRecommands.page = mlRecommands.page - 1; handleGetMusicListRecommand()">
            <Icon type="chevron-left"></Icon>
          </Button>
          <Button shape="circle" :disabled="mlRecommands.totalPages === mlRecommands.page + 1" size="small" type="text" :style="{marginRight: '3px'}" @click="mlRecommands.page = mlRecommands.page + 1; handleGetMusicListRecommand()">
            <Icon type="chevron-right"></Icon>
          </Button>
        </span>
      </h2>
      <Row :gutter="8">
        <Col span="6" :style="{marginBottom: '8px'}" v-for="ml in mlRecommands.mls">
          <Card :style="{borderRadius: '0'}">
            <a class="title" @click="openMusicListInfo(ml)">{{ml.name}}</a>
            <div class="ml-rec-img">
              <img src="ml.photoURL" v-holder="'img=250x160?auto=yes&random=yes&text=图片不见了!'" alt="">
            </div>
          </Card>
        </Col>

        <div v-show="mlRecommands.mls.length === 0" class="ml-no-data" :style="{textAlign: 'center', height: '200px', lineHeight: '200px'}">
          <Icon type="ios-information"></Icon>暂无推荐歌单！
        </div>
      </Row>

      <Row :gutter="40">
        <Col span="12">
          <h2 class="ml-col-title">最新上传
            <span :style="{float: 'right'}" v-show="musics.totalPages">
              <Button shape="circle" size="small" type="text" :disabled="musics.page === 0" @click="musics.page = musics.page - 1; handleGetLastUpload()">
                <Icon type="chevron-left"></Icon>
              </Button>
              <Button shape="circle" size="small" type="text" :disabled="musics.page + 1 === musics.totalPages" :style="{marginRight: '3px'}" @click="musics.page = musics.page + 1; handleGetLastUpload()">
                <Icon type="chevron-right"></Icon>
              </Button>
            </span>
          </h2>
          <Row>
            <Col span="12" :style="{padding: '5px 10px 5px 0'}" v-for="music in musics.datas">
              <Card>
                <div class="clearfix">
                  <div class="music-last-upload">
                    <img src="music.photoURL" v-holder="'img=50x50?auto=yes&size=5&random=yes&text=图片不见了!'" alt="">
                    <div class="music-player-img" @click="musicPlay(music)">
                      <Icon type="play"></Icon>
                    </div>
                  </div>
                  <div :style="{float: 'left', padding: '8px 10px', width: 'calc(100% - 50px)'}">
                    <div class="music-add-wrapper">
                      <p class="music-add-title">{{music.name}}</p>
                      <span class="music-add-ml-icon">
                        <Poptip placement="bottom-end" title="添加到歌单">
                        <!-- musicListsByMyself -->
                          <Icon type="ios-arrow-down"></Icon>
                          <div slot="content">
                            <div v-show="musicListsByMyself.length === 0" class="ml-no-data">
                              <Icon type="ios-information"></Icon>暂无歌单！
                            </div>
                            <ul :style="{maxHeight: '100px', overflowY: 'auto'}">
                              <li @click="handleAddMusicToMusicList(music, ml)" class="music-add-list" v-for="ml in musicListsByMyself">{{ml.name}}</li>
                            </ul>
                          </div>
                        </Poptip>
                      </span>
                    </div>
                    <p :style="{fontSize: '12px', color: '#999'}">{{music.singer || '佚名'}}</p>
                  </div>
                </div>
              </Card>
            </Col>
            <div v-show="musics.datas.length === 0" class="ml-no-data" :style="{textAlign: 'center'}">
              <Icon type="ios-information"></Icon>暂无最新歌曲！
            </div>
          </Row>
        </Col>

        <Col span="12">
          <h2 class="ml-col-title">排行榜</h2>
          <Table :columns="tableCols" :data="tops"></Table>
        </Col>
      </Row>
    </Layout>

    <Layout class="ml-player-wrapper">
      <Row>
        <Col span="6" class="ml-player-btns">
          <Button @click="musicPlayPrev" type="ghost" shape="circle" icon="ios-skipbackward" ></Button>
          <Button type="ghost" shape="circle" :icon="player.paused ? 'ios-play' : 'ios-pause' " size="large"
          @click="player.paused ? handlePlay() : handlePause()"></Button>
          <Button @click="musicPlayNext" type="ghost" shape="circle" icon="ios-skipforward"></Button>
        </Col>
        <Col span="12" :style="{overflow: 'hidden'}">
          <div class="ml-player-image">
            <img v-if="!player.curPhotoURL" v-holder="'img=50x50?auto=yes&size=5&random=yes&text=图片不见了!'" alt="music-img" />
            <img v-else :src="player.curPhotoURL" alt="music-img" />
          </div>
          <div class="ml-player-main">
            <div class="title">{{player.curName || '空'}}
              <span class="gray small"> - {{player.curSinger || '佚名'}}</span>
              <span class="small right">{{Math.round(player.currentTime * 100 / 60) / 100}}<span class="gray">/{{Math.round(player.duration * 100 / 60) / 100}}</span></span>
            </div>
            <Slider show-tip="never" :style="{padding: '0 10px'}" v-model="player.currentTime" :max="player.duration"
              @on-change="handChangePlayerTime">
            </Slider>
          </div>
        </Col>
        <Col span="6">
          <!-- <Icon type="android-volume-mute"></Icon> -->
          <!-- <Icon type="android-volume-down"></Icon> -->
          <!-- <Icon type="android-volume-up"></Icon> -->
          <Icon @click.native="handleLoop(false)" v-if="player.loop" type="ios-loop" class="ml-player-loop"></Icon>
          <Icon @click.native="handleLoop(true)" v-else type="ios-reload" class="ml-player-loop"></Icon>
          <!-- <Icon type="ios-shuffle" class="ml-player-loop"></Icon> -->
          <Icon @click.native="handleMuted(false)" v-if="player.muted" class="ml-player-volume-icon" type="android-volume-off"></Icon>
          <Icon @click.native="handleMuted(true)" v-else-if="player.volume === 0" class="ml-player-volume-icon" type="android-volume-mute"></Icon>
          <Icon @click.native="handleMuted(true)" v-else-if="player.volume < 0.5" class="ml-player-volume-icon" type="android-volume-down"></Icon>
          <Icon @click.native="handleMuted(true)" v-else-if="player.volume >= 0.5" class="ml-player-volume-icon" type="android-volume-up"></Icon>
          <Icon @click.native="handleMuted(true)" v-else class="ml-player-volume-icon" type="android-volume-up"></Icon>
          <Slider class="ml-player-volume" v-model="player.volume * 100"
            @on-input="handleChangeVolume"
          ></Slider>
          <Poptip placement="top-end" width="400">
            <Icon type="drag" size="16" :style="{cursor: 'pointer'}"></Icon>
            <div slot="content">
              <Table height="200" :columns="tableCols" :data="playMusicList"></Table>
            </div>
          </Poptip>
        </Col>
      </Row>
      <audio ref="player"
        :src="player.src"
        class="ml-player-true"
        :loop="player.loop"
        @loadedmetadata="handleInitPlayer"
        @timeupdate="handleUpdateTime"
        @ended="handlePlayComplate"
        @volumechange="handleVolumeChanged"
      >
      </audio>
    </Layout>

    <Button v-show="this.userRoles.find(role => role.authority === 'user' || role.authority === 'admin' || role.authority === 'root')" @click="musicAdd.show = !musicAdd.show" type="primary" shape="circle" class="music-add" icon="plus">
    </Button>

    <Modal
        title="添加音乐"
        v-model="musicAdd.show"
        :loading="musicAdd.loading"
        @on-ok="handleAddMusic"
        :closable="false">
        <Form ref="musicAdd" :model="musicAdd" :rules="ruleMusic" label-position="left" :label-width="100">
            <FormItem label="歌曲名" prop="name">
                <Input v-model="musicAdd.name"></Input>
            </FormItem>
            <FormItem label="歌手">
                <Input v-model="musicAdd.singer"></Input>
            </FormItem>
            <FormItem label="封面URL">
                <Input v-model="musicAdd.photoURL"></Input>
            </FormItem>
            <FormItem label="普通音质URL" prop="qualityURL">
                <Input v-model="musicAdd.qualityURL"></Input>
            </FormItem>
            <FormItem label="歌曲描述">
                <Input v-model="musicAdd.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" ></Input>
            </FormItem>
        </Form>
    </Modal>

    <Modal title="歌单详情" v-model="mlShow" @on-cancel="closeMusicListInfo">
      <div :style="{textAlign: 'right', marginBottom: '10px'}">
        <Button :disabled="!curMusicList || !curMusicList._embedded" type="primary" @click="addMusicList2PlayMusicList(curMusicList)">添加到播放列表</Button>
      </div>

      <div class="ml-info-wrapper">
        <div class="name">歌曲名</div>
        <div class="singer">歌手</div>
        <div class="tool">操作</div>
      </div>
      <div v-if="!curMusicList || !curMusicList._embedded || curMusicList._embedded.musicContian.length === 0">
        <div class="ml-no-data" :style="{textAlign: 'center', lineHeight: '40px'}">
          <Icon type="ios-information"></Icon>暂无音乐！
        </div>
      </div>
      <div v-else class="ml-info-wrapper" v-for="music in curMusicList._embedded.musicContian">
        <div class="name">{{music.name}}</div>
        <div class="singer">{{music.singer}}</div>
        <div class="tool">
          <span class="tool-icon">
            <Poptip placement="bottom-end" title="添加到歌单">
            <!-- musicListsByMyself -->
              <Icon type="ios-arrow-down"></Icon>
              <div slot="content">
                <div v-show="musicListsByMyself.length === 0" class="ml-no-data">
                  <Icon type="ios-information"></Icon>暂无歌单！
                </div>
                <ul :style="{maxHeight: '100px', overflowY: 'auto'}">
                  <li @click="handleAddMusicToMusicList(music, ml)" class="music-add-list" v-for="ml in musicListsByMyself">{{ml.name}}</li>
                </ul>
              </div>
            </Poptip>
          </span>
          <span class="tool-icon" :style="{marginLeft: '20px'}">
            <Icon @click.native="musicPlay(music)" type="play"></Icon>
          </span>
        </div>
      </div>
      <div slot="footer"></div>
    </Modal>
  </Layout>
</template>

<script>
import {mapActions, mapState} from 'vuex'
export default {
  data () {
    return {
      player: {
        paused: true,
        duration: 0,
        currentTime: 0,
        muted: false,
        loop: true,
        volume: 1,
        src: '',
        curName: '',
        curSinger: '',
        curPhotoURL: '',
      },
      playMusicList: [],
      musicListsByMyself: [],
      tableCols: [
        { key: 'name', title: '音乐名' },
        { key: 'singer', title: '歌手' },
      ],
      tops: [],
      mlRecommands: {
        page: 0,
        size: 4,
        totalPages: 0,
        mls: [],
      },
      musicAdd: {
        show: false,
        loading: true,
        name: '',
        singer: '',
        photoURL: '',
        qualityURL: '',
        description: '',
      },
      ruleMusic: {
        name: [{ required: true, message: '歌曲名不能为空', trigger: 'blur' }],
        qualityURL: [{ required: true, message: '资源地址不能为空', trigger: 'blur' }]
      },
      musics: {
        page: 0,
        size: 8,
        totalPages: 0,
        datas: [],
      },
      mlShow: false,
      curMusicList: null,
    }
  },
  methods: {
    ...mapActions(['createMusicListAsync', 'queryMusicListAsync', 'rmMusicListAsync', 'getMusicListAsync', 'uploadMusicAsync', 'queryLastUploadMusics', 'topMusicAysnc', 'musicListCollectedAsync', 'musicListCollectedByMyself', 'addMusicToMusicListAsync']),
    handlePlay () {
      console.log(this.player.src);
      console.log(this.$refs.player.src);
      this.$refs.player.play()
      this.player.paused = this.$refs.player.paused
    },
    handlePause () {
      this.$refs.player.pause()
      this.player.paused = this.$refs.player.paused
    },
    // 初始化值
    handleInitPlayer () {
      this.player.duration = this.$refs.player.duration
      this.player.paused = this.$refs.player.paused
      this.player.volume = this.$refs.player.volume
      this.player.muted = this.$refs.player.muted
    },
    handleUpdateTime () {
      this.player.currentTime = this.$refs.player.currentTime
    },
    // 播放完成
    handlePlayComplate () {
      this.player.paused = this.$refs.player.paused
      let curIndexInPlayList = this.playMusicList.findIndex(musicTmp => {
        console.log(musicTmp.name, this.player.curName)
        console.log(musicTmp.singer, this.player.curSinger)
        return musicTmp.name === this.player.curName && musicTmp.singer === this.player.curSinger
      })
      console.log(curIndexInPlayList);
      if (!this.player.loop && curIndexInPlayList < this.playMusicList.length - 1) {
        this.musicPlay(this.playMusicList[curIndexInPlayList + 1])
      }
    },
    handChangePlayerTime (changeTime) {
      this.$refs.player.currentTime = changeTime
    },
    handleChangeVolume (changeVolume) {
      this.$refs.player.volume = changeVolume / 100
    },
    handleMuted (changeMuted) {
      this.$refs.player.muted = changeMuted
    },
    handleVolumeChanged () {
      this.player.volume = this.$refs.player.volume
      this.player.muted = this.$refs.player.muted
    },
    handleLoop (loop) {
      this.player.loop = loop
    },
    toggleIpt () {
      this.$refs.ipt.style.display === 'none' ? this.$refs.ipt.style.display = 'block' : this.$refs.ipt.style.display = 'none'
    },
    handleAddText ($event) {
      if (this.musicListsByMyself.find((ml) => $event.target.value === ml.name) || !$event.target.value) {
        this.$Message.error('输入有误。')
        $event.target.value = ''
        return
      }
      this.createMusicListAsync($event.target.value)
        .then(res => {
          if (res.data) {
            console.log(res.data);
            $event.target.value = ''
            this.toggleIpt()
            this.handleQueryMusicListByMyself()
          }
        })
        .catch(err => {
          this.$Message.error('创建歌单出错')
        })
    },
    handleQueryMusicListByMyself () {
      this.queryMusicListAsync()
        .then(res => {
          this.musicListsByMyself = res.data._embedded.musicLists
        })
        .catch(err => {
          console.error(err)
        })
    },
    removeMusicList (id) {
      console.log(id)
      this.rmMusicListAsync(id)
        .then(res => {
          this.$Message.info('删除成功')
          this.handleQueryMusicListByMyself()
        })
        .catch(err => {
          this.$Message.error('操作出错')
        })
    },
    handleGetMusicListRecommand () {
      this.getMusicListAsync({
        page: this.mlRecommands.page,
        size: this.mlRecommands.size
      })
      .then(res => {
        this.mlRecommands.mls = res.data._embedded.musicLists
        this.mlRecommands.totalPages = res.data.page.totalPages
      })
      .catch(err => {
        console.error(err)
      })
    },
    handleAddMusic () {
      this.$refs.musicAdd.validate((valid) => {
        if (valid) {
          this.musicAdd.loading = true
          this.uploadMusicAsync({
            description: this.musicAdd.description,
            name: this.musicAdd.name,
            qualityURL: this.musicAdd.qualityURL,
            singer: this.musicAdd.singer,
          })
          .then(res => {
            this.$Message.success('上传歌曲成功！')
            this.musicAdd.description = ''
            this.musicAdd.name = ''
            this.musicAdd.qualityURL = ''
            this.musicAdd.singer = ''
            this.musicAdd.show = false
          })
          .catch(err => {
            this.$Message.error('上传歌曲失败！')
          })
        } else {
            this.$Message.error('输入有误!');
            this.musicAdd.loading = false
        }
      })
    },

    // 获取最新上传
    handleGetLastUpload () {
      this.queryLastUploadMusics({
        page: this.musics.page,
        size: this.musics.size,
      })
      .then(res => {
        this.musics.datas = res.data._embedded.musics
        this.musics.totalPages = res.data.page.totalPages
      })
      .catch(err => {
        console.error(err)
      })
    },
    // 播放音乐
    musicPlay(music) {
      this.player.curName = music.name
      this.player.curSinger = music.singer
      this.player.curPhotoURL = music.photoURL
      this.player.src = music.qualityURL
      if (!this.playMusicList.find(musicTmp => musicTmp.id === music.id)) {
        this.playMusicList.push(music)
      }
      setTimeout(() => {
        this.handlePlay()
      }, 1000)
    },
    musicPlayNext () {
      this.player.paused = this.$refs.player.paused
      let curIndexInPlayList = this.playMusicList.findIndex(musicTmp => {
        return musicTmp.name === this.player.curName && musicTmp.singer === this.player.curSinger
      })
      if (curIndexInPlayList < this.playMusicList.length - 1) {
        this.musicPlay(this.playMusicList[curIndexInPlayList + 1])
      } else {
        this.$Message.info('已经是最后一首歌了')
      }
    },
    musicPlayPrev () {
      this.player.paused = this.$refs.player.paused
      let curIndexInPlayList = this.playMusicList.findIndex(musicTmp => {
        return musicTmp.name === this.player.curName && musicTmp.singer === this.player.curSinger
      })
      if (curIndexInPlayList > 0) {
        this.musicPlay(this.playMusicList[curIndexInPlayList - 1])
      } else {
        this.$Message.info('已经是第一首歌了')
      }
    },
    // 获取排行榜
    handleQueryTopList () {
      this.topMusicAysnc(5)
        .then(res => {
          this.tops = res.data._embedded.musics
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 添加歌曲到歌单
    handleAddMusicToMusicList (music, musicList) {
      // console.log(music._links.self.href);
      this.addMusicToMusicListAsync({musicListId: musicList.id, musicUri: music._links.self.href})
        .then(res => {
          this.$Message.success('添加成功')
        })
        .catch(err => {
          this.$Message.error('添加失败')
        })
    },

    addMusicList2PlayMusicList (ml) {
      ml._embedded.musicContian.map(music => {
        if (!this.playMusicList.find(m => m.id === music.id)) {
          this.playMusicList.push(music)
        }
      })
      this.$Message.success('添加成功')
    },
    openMusicListInfo (ml) {
      console.log('ml', ml)
      this.curMusicList = ml
      this.mlShow = true
    },
    closeMusicListInfo () {
      this.mlShow = false
      this.curMusicList = null
    }
  },
  computed: {
    ...mapState(['userRoles']),
    userId () {
      return this.$store.state.userId
    }
  },
  watch: {
    userId() {
      this.handleQueryMusicListByMyself()
    }
  },

  mounted () {
    this.handleQueryMusicListByMyself()
    this.handleGetMusicListRecommand()
    this.handleGetLastUpload()
    this.handleQueryTopList()

  }
}
</script>

<style lang="css" scoped>
.ml-rec-img {
  height: 160px;
  width: 100%;
}
.ml-rec-img img {
  width: 100%;
  height: 160px;
  object-fit: contain;
  overflow: hidden;
}
.ml-col-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 10px;
  overflow: hidden;
}
.ml-ctrl-icon {
  cursor: pointer;
  font-weight: normal;
  font-size: 14px;
  margin: 0 5px;
}
.ml-player-wrapper {
  position: fixed;
  width: 100%;
  height: 80px;
  line-height: 80px;
  border-top: 1px solid #ddd;
  background-color: #fff;
  bottom: 0;
  left: 0;
  text-align: center;
  overflow: hidden;
  z-index: 999;
}
.ml-player-btns button{
  margin: 0 10px;
}
.ml-player-image {
  float: left;
  width: 50px;
  overflow: hidden;
}
.ml-player-image img{
  width: 50px;
  height: 50px;
  vertical-align: middle;
}
.ml-player-main {
  float: left;
  line-height: normal;
  width: calc(100% - 70px);
  padding-left: 20px;
  text-align: left;
  overflow: hidden;
  vertical-align: middle;
  transform: translate(0, 25%);
}
.ml-player-main .title {
  font-size: 16px;
  color: #333;
}
.ml-player-main .gray{
  color: #999;
}
.ml-player-main .small {
  font-size: 12px;
}
.ml-player-main .right {
  float: right;
}
.ml-player-volume-icon {
  font-size: 16px;
  vertical-align: middle;
  cursor: pointer;
}
.ml-player-volume {
  display: inline-block;
  vertical-align: middle;
  width: calc(100% - 100px);
  padding: 0 20px;
}
.ml-player-true {
  visibility: hidden;
}
.ml-player-loop {
  cursor: pointer;
  vertical-align: middle;
  font-size: 16px;
  margin-right: 10px;
}
.ml-col-group-list {
  height: 48px;
  line-height: 48px;
  font-size: 14px;
  padding-left: 28px;
  color: #999;
  overflow: hidden;
}
.ml-col-add {
  float: right;
  margin-right: 20px;
  cursor: pointer;
}
.ml-col-addText {
  padding: 14px 24px;
}
.ml-col-rm {
  float: right;
  cursor: pointer;
  color: #999;
  display: none;
}
.ml-col-rm:hover {
  color: #666;
}
.ml-menu:hover .ml-col-rm {
  display: inline-block;
}
.ml-no-data{
  padding-left: 25px;
  line-height: 30px;
  font-size: 12px;
  color: #ddd;
}
.ml-no-data i {
  margin-right: 5px;
}
.music-add {
  position: fixed;
  right: 40px;
  bottom: 100px;
}
.music-last-upload {
  float: left;
  width: 50px;
  height: 50px;
  position: relative;
}
.music-player-img {
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  width: 100%;
  height: 100%;
  text-align: center;
  color: #fff;
  line-height: 50px;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.45);
}
.music-last-upload:hover .music-player-img{
  display: block;
}
.ml-recommand-collection {
  float: right;
  margin-right: 10px;
  font-size: 14px;
  color: #666;
}
.music-add-wrapper {
  position: relative;
}
.music-add-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: calc(100% - 20px);
}
.music-add-ml-icon {
  position: absolute;
  right: 0;
  top: 0;
  cursor: pointer;
}

.clearfix:after{
  content:"";
  height:0;
  line-height:0;
  display:block;
  visibility:hidden;
  clear:both;
}
.music-add-list {
  line-height: 25px;
  font-size: 12px;
  color: #666;
  cursor: pointer;
  border-bottom: 1px dashed #ddd;
}
.music-add-list:hover {
  color: #333;
  text-decoration: underline;
}
.ml-info-wrapper {
  border-bottom: 1px solid #eee;
  display: flex;
  line-height: 45px;
}
.ml-info-wrapper:last-child {
  border-bottom: none;
}
.ml-info-wrapper .name {
  flex: 2;

}
.ml-info-wrapper .singer {
  flex: 1;
}
.ml-info-wrapper .tool {
  flex: 1;
}
.tool-icon {
  cursor: pointer;
}
</style>
